<template>
  <div ref="main" style="width: 100%; overflow:hidden; height: 100%">
    <div class="content"><span ref="text">{{text}}</span></div>
    <div ref="overDiv" class="opacity">{{text}}</div>
  </div>
</template>
<script>
export default {
  name: 'scrollText',
  props: {
    text: {
      default: '',
    },
    speed: {
      default: 1
    }
  },
  data () {
    return {
      isScroll: false,
      timer: null,
      offsetLeft: 0,
    }
  },
  watch: {
    isScroll (newValue, oldValue) {
      if (this.isScroll) {

      } else {

      }
    },
    text (newValue, oldValue) {
      this.isOver();
    }
  },
  methods: {
    isOver () {
      let dom = this.$refs.overDiv;
      if (this.text != this.$refs.overDiv.text) {
        this.isScroll = true;
        let w = this.$refs.overDiv.offsetWidth;
        this.$refs.text.style.marginLeft = w + 'px';
        this.offsetLeft = w;
      } else {
        this.isScroll = false;
        this.$refs.text.style.marginLeft = '0px';
      }
    },
    updateScroll () {
      if (this.isScroll) {
        if (!this.$refs.text) {
          return;
        }
        let left = this.$refs.text.offsetWidth * -1;
        let w = this.$refs.overDiv.offsetWidth;
        this.offsetLeft -= this.speed;
        if (this.offsetLeft < left - this.speed * 2) {
          this.offsetLeft = w;
        }
      } else {
        this.offsetLeft = 0;
      }
      this.$refs.text.style.marginLeft = this.offsetLeft + 'px';
    }
  },
  mounted () {
    this.$refs.overDiv.style.width = this.$refs.main.offsetWidth + 'px';
    this.isOver()
    this.timer = setInterval(() => {
      this.updateScroll();
    }, 20)
  },
  beforeDestroy () {
    clearInterval(this.timer);
  }
}
</script>
<style scoped>
.opacity{
  opacity: 0;
  overflow: hidden;
  text-overflow:ellipsis;
  position: absolute;
  z-index: -100;
}
.content{
  width: 100%;
  height: 100%;
}
</style>
